package com.example.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.blog.common.LoginDto;
import com.example.blog.common.Result;
import com.example.blog.entity.User;
import com.example.blog.service.UserService;
import com.example.blog.util.JwtTokenUtil;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ganggang
 * @version 1.0
 * @date 2022/2/9 10:06 下午
 */
@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto) {
        User username = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        if (username == null){
            return Result.fail("用户不存在");
        }
        if (!username.getPassword().equals(loginDto.getPassword())){
            return Result.fail("密码不正确");
        }
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        Map<String,Object> claim = new HashMap<>();
        claim.put("username",username.getUsername());
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwtTokenUtil.doGenerateToken(claim,"ganggang"));
        map.put("userInfo",username);
        map.put("access_token",jwtTokenUtil.doGenerateTokenRefresh(claim,"ganggang"));
        return Result.succ(map);
    }

    @GetMapping("/logout")
    public Result logout(){
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJnYW5nZ2FuZyIsImV4cCI6MTY0NDYyNzg4MCwiaWF0IjoxNjQ0NjI2MDgwLCJ1c2VybmFtZSI6ImdhbmdnYW5nIn0.a6Vo-nOzd4gZvqsl3eBGtfdHmu5lXvBO4d0Xi0HqZZ5veG9hC6MWg5ON_bLYClklxO3XWvFMVd7dan879l97Ow";
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        Claims claimFromToken = jwtTokenUtil.getClaimFromToken(token);
        System.out.println(claimFromToken.get("username"));
        return Result.succ(null);
    }
}
